/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System.Web;
using System.Net.Mail;

namespace Oceanside
{
    public class NetUtils
    {
        public static string GetWanIpAddress()
        {
            string s = "";
            try
            {
                WebClient client = new WebClient();

                // Add a user agent header in case the requested URI contains a query.
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)");

                string baseurl = "http://checkip.dyndns.org/";

                Stream data = client.OpenRead(baseurl);
                StreamReader reader = new StreamReader(data);
                s = reader.ReadToEnd();
                data.Close();
                reader.Close();
                s = s.Replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", "").Replace("</body></html>", "").ToString().Trim();
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return s;
        }

        public static string GetHostName()
        {
            string s = "";
            try
            {
                s = System.Net.Dns.GetHostEntry("localhost").HostName;
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return s;
        }

        [XmlRootAttribute(ElementName = "Response", IsNullable = false)]
        public class IPLocator
        {

            private string city;
            public string City
            {
                get { return city; }
                set { city = value; }
            }

            private string state;
            public string State
            {
                get { return state; }
                set { state = value; }
            }

            private string zip;
            public string Zip
            {
                get { return zip; }
                set { zip = value; }
            }

            private string country;
            public string Country
            {
                get { return country; }
                set { country = value; }
            }

            private string hostName;
            public string HostName
            {
                get { return hostName; }
                set { hostName = value; }
            }
        }

        public static bool SendEmail(string to, string subject, string body, string attachmentFileName)
        {
            ///You can use this function to have the customers exception log file emailed to you.
            bool success = false;
            try
            {
                //using (SmtpClient SmtpServer = new SmtpClient(Constants.ProxyMailServer))
                //{
                //    SmtpServer.Port = Constants.ProxyMailServerPort;
                //    SmtpServer.Credentials = new System.Net.NetworkCredential("yourusername", "youremailpassword");
                //    SmtpServer.EnableSsl = Constants.ProxyMailServerUsesSsl;
                //    SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;

                //    using (MailMessage mail = new MailMessage())
                //    {
                //        mail.From = new MailAddress("youremailaddress");
                //        mail.Subject = subject;
                //        mail.Body = body;

                //        if (attachmentFileName != null)
                //        {
                //            mail.Attachments.Add(new Attachment(attachmentFileName));
                //        }

                //        mail.To.Add(to);

                //        SmtpServer.Send(mail);
                //        success = true;
                //    }
                //}
                return true;
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }

            return success;
        }

        public class IPDetails
        {
            public static IPLocator GetIpInformation(string ipAddy)
            {
                IPDetails ipDetails = new IPDetails();
                IPLocator ipLocater = ipDetails.GetData(ipAddy);
                return ipLocater;
            }
 
            /// <summary>
            /// I used this to see who and where my software was running.
            /// </summary>
            /// <param name="ipAddress"></param>
            /// <returns></returns>
            public IPLocator GetData(string ipAddress)
            {
                IPLocator ipLoc = new IPLocator();
                try
                {
                    string path = "http://ipinfodb.com/ip_locator.php?ip=" + ipAddress;
                    WebClient client = new WebClient();
                    string eResult = client.DownloadString(path);
                    if (eResult != null &eResult.Length > 0)
                    {
                        int index = eResult.IndexOf(ipAddress);
                        eResult = eResult.Substring(index);

                        ///Get the country
                        index = eResult.IndexOf("Country : ");
                        eResult = eResult.Substring(index + "Country : ".Length);
                        index = eResult.IndexOf("<");
                        ipLoc.Country = eResult.Substring(0, index - 1).Trim();

                        ///Get the State
                        index = eResult.IndexOf("State/Province : ");
                        eResult = eResult.Substring(index + "State/Province : ".Length);
                        index = eResult.IndexOf("<");
                        ipLoc.State = eResult.Substring(0, index).Trim();

                        ///Get the City
                        index = eResult.IndexOf("City : ");
                        eResult = eResult.Substring(index + "City : ".Length);
                        index = eResult.IndexOf("<");
                        ipLoc.City = eResult.Substring(0, index).Trim();

                        ///Get the Zipcode
                        index = eResult.IndexOf("Zip or postal code : ");
                        eResult = eResult.Substring(index + "Zip or postal code : ".Length);
                        index = eResult.IndexOf("<");
                        ipLoc.Zip = eResult.Substring(0, index).Trim();

                        ///Get the Hostname
                        index = eResult.IndexOf("Hostname : ");
                        eResult = eResult.Substring(index + "Hostname : ".Length);
                        index = eResult.IndexOf("<");
                        ipLoc.HostName = eResult.Substring(0, index).Trim();
                    }
                }
                catch
                { }
                return ipLoc;
            }
        }
    }
}
